const express = require('express');
const router = express.Router()
const fs = require('fs');
const path = require('path');
const { fileUp, downImg } = require('../service/file')
router
    .put('/', function (req, res) {
        try {
            var fstream;
            req.pipe(req.busboy);
            req.busboy.on('file', function (fieldname, file, filename) {
                let filePath = path.join(__dirname, '../public/') + filename
                fstream = fs.createWriteStream(filePath);
                file.pipe(fstream);
                fstream.on('close', async function () {
                    let form = {
                        pic_path: fs.createReadStream(filePath)
                    }
                    // 上传图片
                    let data = await fileUp(form)
                    let { headers: { location } } = data;
                    location = decodeURIComponent(location);
                    const query = location.split('?')[1];
                    const pram = new URLSearchParams(query);
                    const imgURL = pram.get('query');
                    res.send({ code: 200, imgURL })
                });
            });
        } catch (error) {
            res.send({ code: 400, message: error.message })
        }
    })
    .get('/:url?', async function (req, res) {
        try {
            // 抽离校验
            let { url } = req.params
            if (!url) throw new Error('url不得为空')
            let data = await downImg({ url })
            res.sendFile(data)
        } catch (error) {
            res.send({ code: 400, message: error.message })
        }
    })
module.exports = router
